package com.unittec.drainage.provider.auth.excel.export;

import java.io.File;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.unittec.drainage.provider.ApplicationContextProvider;
import com.unittec.drainage.provider.auth.service.BaseService;
import com.unittec.drainage.provider.common.IConstants;
import com.unittec.drainage.provider.entity.ExportTaskEntity;
import com.unittec.drainage.provider.excel.service.IExportConsumer;
import com.unittec.drainage.provider.excel.utils.ExcelRow;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.provider.scope.ThreadLocalScope;
import com.unittec.drainage.provider.service.HystrixRestTemplateService;
import com.unittec.drainage.provider.utils.DateUtils;
import com.unittec.drainage.provider.utils.OssUtils;
import com.unittec.drainage.provider.utils.UUIDUtils;
import com.unittec.drainage.sdk.auth.request.Req101911;
import com.unittec.drainage.sdk.root.common.CommonConstant;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.internal.exception.BusinessException;

/**
 * @Description:
 * @Author: wuxinwei
 * @CreateDate: 2019年12月4日10:48:55
 */
@Service
public class ExcelExportService {

    @Autowired
    Log log;
    @Autowired
    HystrixRestTemplateService hystrixRestTemplateService;
    @Autowired
    private ExportTaskService exportTaskService;
    @Autowired
    private MqExcelExportProducerService producerService;
    @Autowired
    private BaseService baseService;

    /**
     *
     */
    private static final int DAY = 7;
    /**
     *
     */
    private static final String EXCEL_EXPORT_MAPPING = "excel_export_mapping";

    public <T extends ExcelRow> String export(String consumer, String type, boolean async,
        Map<String, Object> paramMap) {
        log.sysInfoLog("export", "export------->>>>>>>,paramMap:" + paramMap);

        // 获取映射信息
        String typeClass = baseService.getDicMapping(EXCEL_EXPORT_MAPPING, type, paramMap);

        if (StringUtils.isBlank(typeClass)) {
            throw new BusinessException("查询不到相应的导出类型");
        }
        consumer += "ExportConsumer";
        IExportConsumer exportConsumer = (IExportConsumer)ApplicationContextProvider.getBean(consumer);
        System.out.println(exportConsumer.getClass());
        if (StringUtils.isBlank(type)) {
            throw new BusinessException("下载文件模块不能为空");
        }
        paramMap.put("typeClass", typeClass);
        ExportTaskEntity exportTask = new ExportTaskEntity();
        String exportTaskId = UUIDUtils.getId();
        exportTask.setId(exportTaskId);
        exportTask.setStatus(CommonConstant.FILE_STATUS_0);
        exportTask.setConsumer(consumer);
        exportTask.setType(type);
        exportTaskService.save(exportTask);
        paramMap.put("exportTaskId", exportTaskId);
        // 同步导出
        if (async) {
            try {
                File file = null;
                try {
                    file = exportConsumer.consume(exportTask, paramMap);
                    // 文件后缀
                    String fileName = file.getName();
                    String fileTyle = fileName.substring(fileName.lastIndexOf(".") + 1);
                    String downLoadFileName =
                        type + "_" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + "." + fileTyle;
                    String filePath = OssUtils.upload(file,
                        IConstants.EXPORT + "/" + consumer.replace(IConstants.ExportConsumer, ""), downLoadFileName);
                    exportTask.setFilePath(filePath);
                    exportTask.setStatus(CommonConstant.FILE_STATUS_2);
                    exportTask.setOriginalFileName(file.getName());
                    exportTaskService.updateById(exportTask);
                    return OssUtils.getUrl(filePath, DAY);
                } finally {
                    if (file != null) {
                        file.delete();
                    }
                }
            } catch (Exception e) {
                log.sysErrLog("export", e.getMessage(), e);
                exportTask.setStatus(CommonConstant.FILE_STATUS_3);
                exportTask.setRemark(e.getMessage());
                exportTaskService.updateById(exportTask);
                throw new BusinessException(e);
            }

        } else {
            // 异步导出
            asynExportData(consumer, type, paramMap, exportTaskId);
            return null;
        }
    }

    /**
     * 异步导出
     *
     * @param consumer
     * @param type
     * @param paramMap
     * @param exportTaskId
     */
    private void asynExportData(String consumer, String type, Map<String, Object> paramMap, String exportTaskId) {
        GatewayRequest<Req101911> getway = new GatewayRequest<>();
        Req101911 req = new Req101911();
        req.setConsumer(consumer);
        req.setAsync(false);
        req.setType(type);
        req.setParamMap(paramMap);
        req.setExportTaskId(exportTaskId);
        req.setAppId(ThreadLocalScope.getAppId());
        req.setIp(ThreadLocalScope.getAuthData().getIp());
        req.setAppCode(ThreadLocalScope.getAuthData().getAppCode());
        req.setRequestId(ThreadLocalScope.getAuthData().getRequestId());
        req.setTenantId(ThreadLocalScope.getAuthData().getTenantId());
        req.setToken(ThreadLocalScope.getAuthData().getToken());
        req.setUser(ThreadLocalScope.getAuthData().getUser());
        getway.setContent(req);
        producerService.createExcelExportMsg(getway);
    }

    public void asynExportData(Map<String, Object> paramMap) {
        log.sysInfoLog("export", "export------->>>>>>>,paramMap:" + paramMap);

        String exportTaskId = (String)paramMap.get("exportTaskId");
        ExportTaskEntity exportTask = exportTaskService.getById(exportTaskId);
        File file = null;
        try {
            IExportConsumer exportConsumer =
                (IExportConsumer)ApplicationContextProvider.getBean(exportTask.getConsumer());
            // 修改任务状态为处理中
            exportTask.setStatus(CommonConstant.FILE_STATUS_1);
            exportTaskService.updateById(exportTask);
            // 开始处理
            file = exportConsumer.consume(exportTask, paramMap);
            // 上传文件到OSS
            String filePath = OssUtils.upload(file,
                IConstants.EXPORT + "/" + exportTask.getConsumer().replace(IConstants.ExportConsumer, ""),
                file.getName());
            // 修改任务状态为完成
            exportTask.setFilePath(filePath);
            exportTask.setStatus(CommonConstant.FILE_STATUS_2);
            exportTask.setOriginalFileName(file.getName());
            exportTaskService.updateById(exportTask);
        } catch (Exception e) {
            log.sysErrLog("export", e.getMessage(), e);
            // 修改任务状态为异常
            exportTask.setStatus(CommonConstant.FILE_STATUS_3);
            exportTask.setRemark(e.getMessage());
            exportTaskService.updateById(exportTask);
        } finally {
            if (file != null) {
                file.delete();
            }
        }
    }

}
